﻿#-------------------------------------------------------------------------------
# Name:        pyfollow5
# Purpose:
#
# Author:      luaer
#
# Created:     15-12-2009
# Copyright:   (c) Administrator 2009
# Licence:     <GPL2>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import urllib.request
import urllib.parse
import sys,json

class pyfollow5:
    '''the interface to use the api of follow5'''
    def __init__(self, name, passwd, apikey):
        self.name = name
        self.passwd = passwd
        self.api_key = apikey
        self.entry = []
        auth_handler = urllib.request.HTTPBasicAuthHandler()
        auth_handler.add_password(realm='api.follow5.com',
            uri='http://api.follow5.com',
            user=self.name,passwd=self.passwd)
        opener = urllib.request.build_opener(auth_handler)
        # ...and install it globally so it can be used with urlopen.
        urllib.request.install_opener(opener)

    def openurl(self, url):
        '''打开链接，获取json'''
        try:
            f = urllib.request.urlopen(url)
        except IOError:
            print("Oops, error!")
            sys.exit(1)
        #print(f.read().decode('utf-8'))
        self.entry = json.loads(f.read().decode('utf-8'))

    def getNewestShare(self, count):
        '''得到最新的分享条目，count为数量'''
        url = "http://api.follow5.com/api/statuses/public_timeline.json?count={0}&api_key={1}".format(count, self.api_key)
        self.openurl(url)
        return self.entry

    def getAllShare(self, count, page = 1):
        '''获取全部分享包括用户自己、好友、关注的人、悄悄话的分享'''
        url = "http://api.follow5.com/api/statuses/friends_timeline.json?count={0}&page={1}&api_key={2}".format(count, page, self.api_key)
        self.openurl(url)
        return self.entry

def main():
    app = pyfollow5('pyfollow5', 'xiaoxiao', 'D766BE2C290AC55BB9397C7AB410A906')
    entry = app.getAllShare(1)
    print(entry[0]['id'])
    entry = app.getNewestShare(1)
    print(entry[0]['id'])

if __name__ == '__main__':
    main()